package cn.bavelee.pokeinstaller;

import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.LinearLayout;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import cn.bavelee.donatedialog.DonateToMe;

public class PokeInstallerActivity extends AppCompatActivity implements IInstallCallback, ShellUtils.Result {

    private ApkInfo mApkInfo;
    private Animation mRotateAnimation;
    private AppCompatImageView gearImageView;
    private AppCompatTextView titleTextView;
    private AppCompatTextView contentTextView;
    private AppCompatImageView appIconImageView;
    private AppCompatButton installButton;
    private AppCompatButton installSiltentlyButton;
    private AppCompatButton cancelButton;
    private StringBuilder shellResultContent = new StringBuilder();
    private CollapsingToolbarLayout collapsingToolbarLayout;
    private boolean isContentUri = false;
    private Uri uri;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_poke_installer);
        PermissionsHelper.requireStoragePermissions(this);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        LinearLayout progressLayout = findViewById(R.id.progressLayout);
        titleTextView = findViewById(R.id.titleTextView);
        installButton = findViewById(R.id.installButton);
        cancelButton = findViewById(R.id.cancelButton);
        installSiltentlyButton = findViewById(R.id.installSilentlyButton);
        collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.toolbar_layout);
        installButton.setEnabled(true);
        contentTextView = findViewById(R.id.contentTextView);
        gearImageView = (AppCompatImageView) progressLayout.getChildAt(0);
        mRotateAnimation = AnimationUtils.loadAnimation(this, R.anim.gear_always_roate);
        appIconImageView = findViewById(R.id.appIcon);
        LinearInterpolator lin = new LinearInterpolator();
        mRotateAnimation.setInterpolator(lin);
        gearImageView.clearAnimation();
        new ParseApkTask(this, getSourceApkPath()).execute();
    }

    private String getSourceApkPath() {
        if (mApkInfo != null) return mApkInfo.getApkFile().getPath();
        Intent intent = getIntent();
        Uri uri = intent.getData();
        if (uri != null) {
            this.uri = uri;
            if ("content".equalsIgnoreCase(uri.getScheme())) {
                isContentUri = true;
            }
            return uri.getPath();
        }
        return null;
    }

    public void cancelButton(View view) {
        finish();
    }

    public void installButton(View view) {
        if (installButton.getText().toString().equalsIgnoreCase(getString(R.string.open_app))) {
            Intent intent = getPackageManager().getLaunchIntentForPackage(mApkInfo.getPackageName());
            startActivity(intent);
            finish();
        } else {
            new InstallApkTask(mApkInfo, this, this).execute();
        }
    }

    @Override
    public void onPreInstall(ApkInfo apkInfo) {
        titleTextView.setText(R.string.installing);
        gearImageView.startAnimation(mRotateAnimation);
        installButton.setEnabled(false);
        installSiltentlyButton.setEnabled(false);
    }

    @Override
    public void onInstalled(ApkInfo apkInfo, boolean success) {
        installButton.setEnabled(false);
        installSiltentlyButton.setEnabled(false);
        gearImageView.clearAnimation();
        if (success) {
            Toast.makeText(getApplicationContext(), getString(R.string.apk_installed, apkInfo.getAppName()), Toast.LENGTH_SHORT).show();
            titleTextView.setText(R.string.successful);
            installButton.setEnabled(true);
            installButton.setText(R.string.open_app);
        } else {
            titleTextView.setText(R.string.failed);
        }
        if (isContentUri) mApkInfo.getApkFile().delete();
    }

    private void appendShellResultContent(final String text) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                shellResultContent.append(text).append("\n");
                contentTextView.setText(shellResultContent.toString());
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (isContentUri) mApkInfo.getApkFile().delete();
    }

    @Override
    public void onStdout(String text) {
        appendShellResultContent(text);
    }

    @Override
    public void onStderr(String text) {
        appendShellResultContent(text);
    }

    @Override
    public void onCommand(String command) {
        appendShellResultContent(command);
    }

    @Override
    public void onFinish(int resultCode) {
        appendShellResultContent(getString(R.string.install_finished_with_result_code, resultCode));
    }


    public void installSilentlyButton(View view) {
        Intent intent = new Intent(this, BackgroundInstallActivity.class);
        intent.setData(uri);
        startActivity(intent);
        finish();
    }

    public void donateButton(View view) {
        DonateToMe.show(this);
    }

    private class ParseApkTask extends AsyncTask<Void, Void, ApkInfo> {
        PokeInstallerActivity activity;
        String apkPath;

        public ParseApkTask(PokeInstallerActivity activity, String apkPath) {
            this.activity = activity;
            this.apkPath = apkPath;
        }

        @Override
        protected void onPostExecute(ApkInfo apkInfo) {
            super.onPostExecute(apkInfo);
            if (apkInfo == null) return;
            mApkInfo = apkInfo;
            titleTextView.setText(mApkInfo.getPackageName());
            collapsingToolbarLayout.setTitle(mApkInfo.getAppName());
            appIconImageView.setImageDrawable(apkInfo.getIcon());
            shellResultContent.setLength(0);
            shellResultContent.append(getString(R.string.info_app_name, apkInfo.getAppName())).append("\n");
            shellResultContent.append(getString(R.string.info_pkg_name, apkInfo.getPackageName())).append("\n");
            shellResultContent.append(getString(R.string.info_apk_path, apkInfo.getApkFile().getPath())).append("\n");
            shellResultContent.append(getString(R.string.info_version, apkInfo.getVersion())).append("\n");
            shellResultContent.append(getString(R.string.info_installed_app, apkInfo.hasInstalledApp() ? getString(R.string.yes) : getString(R.string.no))).append("\n");
            shellResultContent.append(getString(R.string.info_installed_version, apkInfo.getInstalledVersion())).append("\n");
            shellResultContent.append("\n\n");
            contentTextView.setText(shellResultContent.toString());
            installButton.setEnabled(true);
        }

        @Override
        protected ApkInfo doInBackground(Void... voids) {
            String realApkPath = apkPath;
            if (isContentUri) {
                File tempFile = new File(getExternalCacheDir(), System.currentTimeMillis() + ".apk");
                try {
                    PokeInstaller.writeFile(getContentResolver().openInputStream(uri), tempFile);
                    realApkPath = tempFile.getPath();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return PokeInstaller.getApkInfo(activity, realApkPath);
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            titleTextView.setText(R.string.parsing);
            installButton.setEnabled(false);
        }

    }

}
